package com.practice.web.interceptor;

import com.practice.domain.user.User;
import com.practice.exception.PracticeException;
import com.practice.web.controller.BaseController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Created by Administrator on 2016/8/20.
 */
public class AccessInterceptor extends HandlerInterceptorAdapter {
  private static final List<String> noLoginResources = new ArrayList<String>()
  {
    {
      add("/login");
      add("/register");
      add("/checkUsername");
      add("/checkEmail");
    }
  };

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) throws Exception {

    // 不需要进行访问控制的资源过滤
    String uri = request.getRequestURI();
    boolean needLogin = true;
    if ("/".equals(uri)) {
      needLogin = false;
    } else {
      for (String resource : noLoginResources) {
        if (uri.endsWith(resource)) {
          needLogin = false;
          break;
        }
      }
    }

    User user;
    if (needLogin) {
      user = (User) request.getSession().getAttribute(BaseController.SESSION_USER_KEY);
      if (null == user) {
        response.sendRedirect("/Practice/login.jsp");
        return false;
      }
    }
    return true;
  }
}
